<script setup>
import { ref, onMounted } from "vue";
import { getCourses, getAllChapters, getAllSections, deleteChapters, deleteSections } from '@/api/post.js';

// 本地数据存储
const courses = ref([]);
const chapters = ref([]);
const sections = ref([]);

// 树形结构数据
const treeData = ref([]);

const emit = defineEmits(['add-chapter', 'add-section', 'delete-chapter', 'delete-section'])

// 获取课程、章节和小节数据
function fetchData() {
  Promise.all([getCourses(), getAllChapters(), getAllSections()])
    .then(([coursesRes, chaptersRes, sectionsRes]) => {
      courses.value = coursesRes.data.courses;
      chapters.value = chaptersRes.data.chapters;
      sections.value = sectionsRes.data.sections;
      // 数据获取完成后，构建树形结构
      buildTreeData();
    })
    .catch((e) => console.error("Failed to fetch data:", e));
}

// 构建树形结构数据
function buildTreeData() {
  treeData.value = courses.value.map((course) => {
    // 找到属于当前课程的章节
    const courseChapters = chapters.value.filter(
      (chapter) => chapter.courseId === course.courseId
    );

    // 构建章节节点
    const chapterNodes = courseChapters.map((chapter) => {
      // 找到属于当前章节的小节
      const chapterSections = sections.value.filter(
        (section) => section.chapterId === chapter.chapterId
      );

      // 构建小节节点
      const sectionNodes = chapterSections.map((section) => ({
        label: section.title,
        id: section.sectionId,
        nodeType: "section",
        ...section, // 保留小节的原始字段
      }));

      return {
        label: chapter.title,
        id: chapter.chapterId,
        nodeType: "chapter",
        children: sectionNodes,
        ...chapter, // 保留章节的原始字段
      };
    });

    return {
      label: course.title,
      id: course.courseId,
      nodeType: "course",
      children: chapterNodes,
      ...course, // 保留课程的原始字段
    };
  });
}

// 组件加载成功后调用 fetchData
onMounted(() => {
  fetchData();
});

// 点击节点时的回调
const handleNodeClick = (data) => {
  console.log("Clicked node:", data);
};

// 删除章节
const handleDeleteChapter = (chapterId) => {
  if (window.confirm("确定删除章节吗？")) {
    deleteChapters(chapterId)
      .then(() => {
        // 删除成功后，更新本地数据
        chapters.value = chapters.value.filter(chapter => chapter.chapterId !== chapterId);
        // 重新构建树形结构
        buildTreeData();
      })
      .catch(error => {
        console.error('删除章节失败:', error);
      });
  }
};

// 删除小节
const handleDeleteSection = (sectionId) => {
  if (window.confirm("确定删除小节吗？")) {
    deleteSections(sectionId)
      .then(() => {
        // 删除成功后，更新本地数据
        sections.value = sections.value.filter(section => section.sectionId !== sectionId);
        // 重新构建树形结构
        buildTreeData();
      })
      .catch(error => {
        console.error('删除小节失败:', error);
      });
  }
};

// 树形组件的配置
const defaultProps = {
  children: "children",
  label: "label",
};
</script>

<template>
  <div class="directory">
    <el-tree
      :data="treeData"
      :props="defaultProps"
      @node-click="handleNodeClick"
      node-key="id"
      default-expand-all
      :expand-on-click-node="false"
    >
      <!-- 自定义节点内容 -->
      <template #default="{ node, data }">
        <div class="custom-tree-node">
          <span>{{ node.label }}</span>
          <!-- 根据节点类型显示按钮 -->
          <el-button
            v-if="data.nodeType === 'course'"
            type="primary"
            size="small"
            class="btn-chapter"
            @click.stop="emit('add-chapter', data.id)"
          >
            添加章节
          </el-button>
          <el-button
            v-if="data.nodeType === 'chapter'"
            type="danger"
            size="small"
            class="btn-delete"
            @click.stop="handleDeleteChapter(data.id)"
          >
            删除章节
          </el-button>
          <el-button
            v-if="data.nodeType === 'chapter'"
            type="primary"
            size="small"
            class="btn-section"
            @click.stop="emit('add-section', data.id)"
          >
            添加小节
          </el-button>
          <el-button
            v-if="data.nodeType === 'section'"
            type="danger"
            size="small"
            class="btn-delete"
            @click.stop="handleDeleteSection(data.id)"
          >
            删除小节
          </el-button>
        </div>
      </template>
    </el-tree>
  </div>
</template>

<style scoped>
.directory {
  width: 300px;
  overflow-y: auto;
  border-right: 1px solid #ddd;
  padding: 20px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 4px;
}

.btn-chapter,
.btn-section,
.btn-delete {
  margin-left: 8px;
}
</style>
